package com.wangxl.shiro.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 自定义Realm
 * 
 * @author wangxl
 *
 */
public class MyRealm extends AuthorizingRealm
{

	/**
	 * 用于授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
	{
		System.out.println("====用于授权======doGetAuthorizationInfo========");
		/* 为用户授权 */
		/* 拿到用户名 */
		String username = principalCollection.getPrimaryPrincipal() + "" ;
		
		/* 权限集合 */
		List<String> permissList = new ArrayList<String>();
		permissList.add("users:insert");
		permissList.add("users:delete");
		
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRole("role1");
		
		/* 将权限放到 SimpleAuthorizationInfo 中*/
		for (Iterator iterator = permissList.iterator(); iterator.hasNext();)
		{
			String permiss = (String) iterator.next();
			simpleAuthorizationInfo.addStringPermission(permiss);
		}
		return simpleAuthorizationInfo;
	}

	/**
	 * 用户验证
	 */
	@Override
	/*
	 * 木有采用任何的密码加密
	 * */
	/*protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException
	{
		System.out.println("====用户验证======doGetAuthenticationInfo========");
		 写上从数据库中查询 
		String username = "zhangsan";
		String pass = "111111" ; 
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, pass, this.getName());
		return simpleAuthenticationInfo;
	}*/
	
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException
	{
		System.out.println("====用户验证======doGetAuthenticationInfo========");
		/* 写上从数据库中查询 */
		String username = "zhangsan";
		String pass = "4de0fe9cf9f47ce5af891d6182d6c4b7" ; 
		/* 采用加盐,盐值一定要一致 */
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, pass, ByteSource.Util.bytes("test"),
				this.getName());
		return simpleAuthenticationInfo;
	}

}
